﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using Dora.Tools.Enums.AdminUser;
using SqlSugar;
using Surging.Core.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Repository.Repositorys
{
    /// <summary>
    /// 旅行社用户表仓储层
    /// </summary>
    public class TasUserRepository : SqlSugarRepository<TasUserEntity, Guid>
    {
        private ISugarUnitOfWork _unitOfWork;
        public TasUserRepository(ISugarUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }


        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<TasUserListDto>> GetPageList(TasUserQueryDto input)
        {
            try
            {
                var searchPredict = _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity, TasUserEntity>((ou, u) => new object[] { JoinType.Inner, ou.UserId == u.Id })
                .Where((ou, u) => u.IsDeleted == 0)
                .WhereIF(input.OrgId.HasValue, (ou, u) => ou.OrgId == input.OrgId)
                .WhereIF(input.IsDisabled.HasValue, (ou, u) => u.IsDisabled == input.IsDisabled)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Keywords), (ou, u) => u.Mobile.Contains(input.Keywords.Trim()) || u.UserName.Contains(input.Keywords.Trim())
                || u.RealName.Contains(input.Keywords.Trim()) || u.Email.Contains(input.Keywords.Trim()))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Mobile), (ou, u) => u.Mobile.Contains(input.Mobile.Trim()))
                .WhereIF(!string.IsNullOrWhiteSpace(input.RealName), (ou, u) => u.RealName.Contains(input.RealName.Trim()))
                .WhereIF(input.UserIdList?.Count>0, (ou, u) =>input.UserIdList.Contains(u.Id))
                .OrderBy((ou,u) => u.CreatedTime, OrderByType.Desc)
                .Select((ou, u) => new TasUserListDto
                {
                    Id = u.Id,
                    UserName = u.UserName,
                    Mobile = u.Mobile,
                    MobileIsVerified = u.MobileIsVerified,
                    Email = u.Email,
                    EmailIsVerified = u.EmailIsVerified,
                    RealName = u.RealName,
                    Sex = u.Sex,
                    Sort = u.Sort,
                    IsDisabled = ou.IsDisabled,
                    IsFrozen = u.IsFrozen,
                    IsSuperAdmin = u.IsSuperAdmin,
                    Avatar = u.Avatar,
                    Remark = u.Remark,
                    IsAdmin = ou.IsAdmin,
                    IsLeader = ou.IsLeader,
                    CreatedTime = u.CreatedTime,
                    JobNumber = ou.JobNumber,
                    OrgId = ou.OrgId
                });

                var totalCount = await searchPredict.CountAsync();
                var pageList = await searchPredict.ToPageListAsync(input.PageIndex, input.PageSize);

                var page = new PageDataList<TasUserListDto>(totalCount, pageList, input.PageIndex, input.PageSize);
                return page;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
            
        }

        /// <summary>
        /// 分页获取分社及负责人数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<TasUserListDto>> GetBranchLeaderPageList(TasUserQueryDto input)
        {
            try
            {
                var searchPredict = _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity, TasUserEntity,OrganizationEntity>((ou, u,o) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                    JoinType.Inner,ou.OrgId==o.Id
                })
                .Where((ou, u, o) => u.IsDeleted == 0&&ou.IsLeader==1 && o.OrgLevel == (int)OrgLevel.Branch)
                .WhereIF(input.OrgId.HasValue, (ou, u, o) => ou.OrgId == input.OrgId)
                .WhereIF(input.OrgParentId.HasValue, (ou, u, o) => o.ParentId == input.OrgParentId)
                .WhereIF(input.IsDisabled.HasValue, (ou, u, o) => ou.IsDisabled == input.IsDisabled)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Keywords), (ou, u, o) => u.Mobile.Contains(input.Keywords) || u.UserName.Contains(input.Keywords)
                || u.RealName.Contains(input.Keywords) || u.Email.Contains(input.Keywords))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Mobile), (ou, u, o) => u.Mobile.Contains(input.Mobile))
                .WhereIF(!string.IsNullOrWhiteSpace(input.RealName), (ou, u, o) => u.RealName.Contains(input.RealName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrgName), (ou, u, o) => o.Name.Contains(input.OrgName))
                .OrderBy((ou, u, o) => u.CreatedTime, OrderByType.Desc)
                .Select((ou, u, o) => new TasUserListDto
                {
                    Id = u.Id,
                    UserName = u.UserName,
                    Mobile = u.Mobile,
                    MobileIsVerified = u.MobileIsVerified,
                    Email = u.Email,
                    EmailIsVerified = u.EmailIsVerified,
                    RealName = u.RealName,
                    Sex = u.Sex,
                    Sort = u.Sort,
                    IsDisabled = ou.IsDisabled,
                    IsFrozen = ou.IsFrozen,
                    IsSuperAdmin = u.IsSuperAdmin,
                    Avatar = u.Avatar,
                    Remark = u.Remark,
                    IsAdmin = ou.IsAdmin,
                    IsLeader = ou.IsLeader,
                    OrgName=o.Name,
                    OrgId=o.Id,
                    CreatedTime=u.CreatedTime,
                    SubShopCount = SqlFunc.Subqueryable<OrganizationEntity>().Where(os => (os.ParentId == o.Id&&os.OrgLevel== (int)OrgLevel.Store) || (os.ParentId == o.Id && os.OrgLevel == (int)OrgLevel.DirectlyUnder)).Count()
                });

                var totalCount = await searchPredict.CountAsync();
                var pageList = await searchPredict.ToPageListAsync(input.PageIndex, input.PageSize);

                var page = new PageDataList<TasUserListDto>(totalCount, pageList, input.PageIndex, input.PageSize);
                return page;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
            
        }

        /// <summary>
        /// 分页获取门店(普通门店及直属门店)及负责人数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<TasUserListDto>> GetShopLeaderPageList(TasUserQueryDto input)
        {
            try
            {
                var searchPredict = _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity, TasUserEntity, OrganizationEntity>((ou, u, o) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                    JoinType.Inner,ou.OrgId==o.Id
                })
                //.Where((ou, u, o) => u.IsDeleted == 0 && ou.IsLeader == 1 && (o.OrgLevel == (int)OrgLevel.Store|| o.OrgLevel == (int)OrgLevel.DirectlyUnder))
                .Where((ou, u, o) => u.IsDeleted == 0 && ou.IsLeader == 1 && o.OrgLevel == input.OrgLevel)
                .WhereIF(input.OrgId.HasValue, (ou, u, o) => ou.OrgId == input.OrgId)
                .WhereIF(input.OrgParentId.HasValue, (ou, u, o) => o.ParentId == input.OrgParentId)
                .WhereIF(input.IsDisabled.HasValue, (ou, u, o) => ou.IsDisabled == input.IsDisabled)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Keywords), (ou, u, o) => u.Mobile.Contains(input.Keywords) || u.UserName.Contains(input.Keywords)
                || u.RealName.Contains(input.Keywords) || u.Email.Contains(input.Keywords))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Mobile), (ou, u, o) => u.Mobile.Contains(input.Mobile))
                .WhereIF(!string.IsNullOrWhiteSpace(input.RealName), (ou, u, o) => u.RealName.Contains(input.RealName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrgName), (ou, u, o) => o.Name.Contains(input.OrgName))
                .OrderBy((ou, u, o) => u.CreatedTime, OrderByType.Desc)
                .Select((ou, u, o) => new TasUserListDto
                {
                    Id = u.Id,
                    UserName = u.UserName,
                    Mobile = u.Mobile,
                    MobileIsVerified = u.MobileIsVerified,
                    Email = u.Email,
                    EmailIsVerified = u.EmailIsVerified,
                    RealName = u.RealName,
                    Sex = u.Sex,
                    Sort = u.Sort,
                    IsDisabled = ou.IsDisabled,
                    IsFrozen = ou.IsFrozen,
                    IsSuperAdmin = u.IsSuperAdmin,
                    Avatar = u.Avatar,
                    Remark = u.Remark,
                    IsAdmin = ou.IsAdmin,
                    IsLeader = ou.IsLeader,
                    OrgName = o.Name,
                    OrgId = o.Id,
                    CreatedTime = u.CreatedTime
                });

                var totalCount = await searchPredict.CountAsync();
                var pageList = await searchPredict.ToPageListAsync(input.PageIndex, input.PageSize);

                var page = new PageDataList<TasUserListDto>(totalCount, pageList, input.PageIndex, input.PageSize);
                return page;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }

        }

        /// <summary>
        /// 获取子账号数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<TasUserListDto>> GetSubUserList(TasUserQueryDto input)
        {
            try
            {
                var searchPredict = _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity, TasUserEntity, OrganizationEntity, TasUserRoleMapEntity, RoleEntity>((ou, u, o, ro, r) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                    JoinType.Inner, ou.OrgId == o.Id,
                    JoinType.Left, (ro.UserId == u.Id && ro.OrgId == input.OrgId ),
                    JoinType.Left, ro.RoleId == r.Id
                })
                .Where((ou, u, o) => u.IsDeleted == 0 && ou.IsLeader == 0 && o.OrgLevel == input.OrgLevel)
                .WhereIF(input.OrgId.HasValue, (ou, u, o) => ou.OrgId == input.OrgId)
                .WhereIF(input.OrgParentId.HasValue, (ou, u, o) => o.ParentId == input.OrgParentId)
                .WhereIF(input.IsDisabled.HasValue, (ou, u, o) => ou.IsDisabled == input.IsDisabled)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Keywords), (ou, u, o) => u.Mobile.Contains(input.Keywords) || u.UserName.Contains(input.Keywords)
                || u.RealName.Contains(input.Keywords) || u.Email.Contains(input.Keywords))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Mobile), (ou, u, o) => u.Mobile.Contains(input.Mobile))
                .WhereIF(!string.IsNullOrWhiteSpace(input.RealName), (ou, u, o) => u.RealName.Contains(input.RealName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrgName), (ou, u, o) => o.Name.Contains(input.OrgName))
                .OrderBy((ou, u, o) => u.CreatedTime, OrderByType.Desc)
                .Select((ou, u, o, ro, r) => new TasUserListDto
                {
                    Id = u.Id,
                    UserName = u.UserName,
                    Mobile = u.Mobile,
                    MobileIsVerified = u.MobileIsVerified,
                    Email = u.Email,
                    EmailIsVerified = u.EmailIsVerified,
                    RealName = u.RealName,
                    Sex = u.Sex,
                    Sort = u.Sort,
                    IsDisabled = ou.IsDisabled,
                    IsFrozen = ou.IsFrozen,
                    IsSuperAdmin = u.IsSuperAdmin,
                    Avatar = u.Avatar,
                    Remark = u.Remark,
                    IsAdmin = ou.IsAdmin,
                    IsLeader = ou.IsLeader,
                    OrgName = o.Name,
                    OrgId = o.Id,
                    RoleName = r.Name,
                    CreatedTime = u.CreatedTime
                });

                return (await searchPredict.Distinct().ToListAsync()) ?? new List<TasUserListDto>();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 根据用户名获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<TasUserEntity> GetByUserName(string userName)
        {
            return await _unitOfWork.QueryClient.Queryable<TasUserEntity>().FirstAsync(item => item.UserName == userName);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> Delete(Guid id)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .UpdateColumns(it => new TasUserEntity() { IsDeleted = 1, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 根据手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<TasUserEntity> GetByMobile(string mobile)
        {
            return await _unitOfWork.QueryClient.Queryable<TasUserEntity>().FirstAsync(item => item.Mobile == mobile);
        }

        /// <summary>
        /// 根据验证后的手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<TasUserEntity> GetByVerifiedMobile(string mobile)
        {
            return await _unitOfWork.QueryClient.Queryable<TasUserEntity>().FirstAsync(item => item.Mobile == mobile && item.MobileIsVerified == 1);
        }

        /// <summary>
        /// 根据手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<TasUserEntity> GetByEmail(string email)
        {
            return await _unitOfWork.QueryClient.Queryable<TasUserEntity>().FirstAsync(item => item.Email == email);
        }

        /// <summary>
        /// 根据验证后的手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<TasUserEntity> GetByVerifiedEmail(string email)
        {
            return await _unitOfWork.QueryClient.Queryable<TasUserEntity>().FirstAsync(item => item.Email == email && item.EmailIsVerified == 1);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdatePassword(TasUserEntity entity)
        {
            //var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new { it.Password, it.UpdatedTime }).ExecuteCommandAsync() > 0;
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .UpdateColumns(it => new TasUserEntity() { Password = entity.Password, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }
        

        /// <summary>
        /// 禁用/启用用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> IsDisabled(TasUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .UpdateColumns(it => new TasUserEntity() { IsDisabled = entity.IsDisabled, UpdatedTime = entity.UpdatedTime, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 冻结/解冻用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> IsFrozen(TasUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .UpdateColumns(it => new TasUserEntity() { IsFrozen = entity.IsFrozen, UpdatedTime = entity.UpdatedTime, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<bool> Update(TasUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new
            {
                //it.Id,
                //it.UserName,
                //it.Password,
                //it.PasswordSalt,
                it.Mobile,
                //it.MobileIsVerified,
                it.Email,
                //it.EmailIsVerified,
                it.RealName,
                it.Sex,
                it.IDCardNO,
                it.Sort,
                //it.IsDisabled,
                //it.IsFrozen,
                //it.IsSuperAdmin,
                it.Avatar,
                it.Remark,
                //it.IsDeleted,
                //it.CreatedUserId,
                //it.CreatedUserName,
                //it.CreatedTime,
                it.UpdatedUserId,
                it.UpdatedUserName,
                it.UpdatedTime,
            }).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 验证后的手机号是否存在
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExistVerifiedMobile(string mobile, Guid id)
        {
            return await _unitOfWork.QueryClient.Queryable<TasUserEntity>().Where(it => it.Mobile == mobile && it.MobileIsVerified == 1 && it.IsDeleted == 0 && it.Id != id).CountAsync() > 0;
        }

        /// <summary>
        /// 修改最后访问的OrgId
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateLastOrgId(TasUserEntity entity)
        {
            //var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new { it.Password, it.UpdatedTime }).ExecuteCommandAsync() > 0;
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .UpdateColumns(it => new TasUserEntity() { LastOrgId = entity.LastOrgId })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 验证后的身份证号是否存在
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExistVerifiedIdCardNo(string idCardNo, Guid id)
        {
            return await _unitOfWork.QueryClient.Queryable<TasUserEntity>().Where(it => it.IDCardNO == idCardNo && it.IsDeleted == 0 && it.Id != id).CountAsync() > 0;
        }

        /// <summary>
        /// 修改用户基本信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateBaseInfo(TasUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .SetColumns(it => new TasUserEntity() { Avatar = entity.Avatar, Sex = entity.Sex, Phone = entity.Phone, Email = entity.Email, QQAccount = entity.QQAccount, WxAccount = entity.WxAccount, PersonalNote = entity.PersonalNote, UpdatedTime = DateTime.Now, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 修改用户基本信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateMobile(TasUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .SetColumns(it => new TasUserEntity() { Mobile = entity.Mobile, UpdatedTime = DateTime.Now})
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 获取tasuser及组织机构信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<TasUserListDto> GetByUserIdAndOrgId(Guid userId,int orgId)
        {
            try
            {
                var result =await _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity, TasUserEntity, OrganizationEntity>((ou, u, o) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                    JoinType.Inner,ou.OrgId==o.Id
                })
                .Where((ou, u, o) => u.IsDeleted == 0&&ou.UserId==userId&&ou.OrgId==orgId )
                .Select((ou, u, o) => new TasUserListDto
                {
                    Id = u.Id,
                    UserName = u.UserName,
                    Mobile = u.Mobile,
                    MobileIsVerified = u.MobileIsVerified,
                    Email = u.Email,
                    EmailIsVerified = u.EmailIsVerified,
                    RealName = u.RealName,
                    Sex = u.Sex,
                    Sort = u.Sort,
                    IsDisabled = u.IsDisabled,
                    IsFrozen = u.IsFrozen,
                    IsSuperAdmin = u.IsSuperAdmin,
                    Avatar = u.Avatar,
                    Remark = u.Remark,
                    IsAdmin = ou.IsAdmin,
                    IsLeader = ou.IsLeader,
                    OrgName = o.Name,
                    CreatedTime = u.CreatedTime
                })
                .FirstAsync()
                ;
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }

        }

        /// <summary>
        /// 修改用户基本信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateRemark(TasUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasUserEntity>()
                .SetColumns(it => new TasUserEntity() { Remark = entity.Remark, UpdatedTime = DateTime.Now, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 通过组织机构id和关键字查询用户信息
        /// </summary>
        /// <param name="userIdList"></param>
        /// <returns></returns>
        public async Task<List<TasUserEntity>> GetListByOrgIdAndKeywords(int orgId, string keywords)
        {
            var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity>((u, ou) => new object[] {
                JoinType.Inner, u.Id == ou.UserId,
            })
                .Where((u, ou) => ou.OrgId==orgId)
                .WhereIF(!string.IsNullOrWhiteSpace(keywords), (u, ou) => u.RealName.Contains(keywords))
                .Select((u, ou) => u).ToListAsync();
            return result;
        }


        /// <summary>
        /// 通过组织机构id查询用户信息（排除某个用户）
        /// </summary>
        /// <param name="userIdList"></param>
        /// <returns></returns>
        public async Task<List<TasUserBriefListDto>> GetBriefListByOrgIdButOne(int orgId, Guid userId)
        {
            var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity, OrganizationEntity>((u, ou, o) => new object[] {
                JoinType.Inner, u.Id == ou.UserId,
                JoinType.Inner, ou.OrgId == o.Id,
            })
                .Where((u, ou, o) => ou.OrgId == orgId)
                .Where((u, ou, o) => u.Id != userId)
                .OrderBy((u, ou, o) => u.RealName, OrderByType.Asc)
                .Select((u, ou, o) => new TasUserBriefListDto() {
                    Id=u.Id,
                    Mobile=u.Mobile,
                    Email=u.Email,
                    RealName=u.RealName,
                    Sex=u.Sex,
                    Avatar = u.Avatar,
                    HxUserName = ou.HxUserName,
                    OrgId = ou.OrgId,
                    OrgName = o.Name
                }).ToListAsync();
            return result;
        }

        /// <summary>
        /// 通过组织机构id查询用户信息（排除某个用户）
        /// </summary>
        /// <param name="userIdList"></param>
        /// <returns></returns>
        public async Task<List<TasUserBriefListDto>> GetBriefListByOrgId(int orgId)
        {
            var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity, OrganizationEntity>((u, ou, o) => new object[] {
                JoinType.Inner, u.Id == ou.UserId,
                JoinType.Inner, ou.OrgId == o.Id,
            })
                .Where((u, ou, o) => ou.OrgId == orgId)
                .OrderBy((u, ou, o) => ou.IsLeader, OrderByType.Desc)
                .OrderBy((u, ou, o) => u.RealName, OrderByType.Asc)
                .Select((u, ou, o) => new TasUserBriefListDto()
                {
                    Id = u.Id,
                    Mobile = u.Mobile,
                    Email = u.Email,
                    RealName = u.RealName,
                    Sex = u.Sex,
                    Avatar = u.Avatar,
                    HxUserName = ou.HxUserName,
                    JobNumber = ou.JobNumber,
                    OrgId = ou.OrgId,
                    OrgName = o.Name
                })
                .ToListAsync();
            return result;
        }

        /// <summary>
        /// 通过组织机构id集合查询用户信息
        /// </summary>
        /// <param name="userIdList"></param>
        /// <returns></returns>
        public async Task<List<TasUserBriefListDto>> GetBriefListByOrgIds(List<int> orgId)
        {
            var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity, OrganizationEntity>((u, ou, o) => new object[] {
                JoinType.Inner, u.Id == ou.UserId,
                JoinType.Inner, ou.OrgId == o.Id,
            })
                .Where((u, ou, o) => orgId.Contains(ou.OrgId))
                .OrderBy((u, ou, o) => ou.IsLeader, OrderByType.Desc)
                .OrderBy((u, ou, o) => u.RealName, OrderByType.Asc)
                .Select((u, ou, o) => new TasUserBriefListDto()
                {
                    Id = u.Id,
                    Mobile = u.Mobile,
                    Email = u.Email,
                    RealName = u.RealName,
                    Sex = u.Sex,
                    Avatar = u.Avatar,
                    HxUserName = ou.HxUserName,
                    JobNumber = ou.JobNumber,
                    OrgId = ou.OrgId,
                    OrgName = o.Name,
                    IsLeader=ou.IsLeader,
                })
                .ToListAsync();
            return result;
        }


        /// <summary>
        /// 根据orgId获取org的负责人
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<TasUserEntity> GetOrgLeaderByOrgId(int orgId)
        {
            try
            {
                var result =await _unitOfWork.QueryClient.Queryable<TasUserEntity,TasOrgUserMapEntity>(( u,ou) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                })
                //.Where(( u,ou) => u.IsDeleted == 0 && ou.IsLeader == 1 && (o.OrgLevel == (int)OrgLevel.Store|| o.OrgLevel == (int)OrgLevel.DirectlyUnder))
                .Where(( u,ou) => u.IsDeleted == 0 && ou.IsLeader == 1 && ou.OrgId == orgId)
                .Select(( u,ou) =>u).FirstAsync();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }
        /// <summary>
        /// 根据组织机构ID获取负责人信息包括手机号和OPENDID
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<LeaderInfo> GetLeaderInfoByOrgId(int orgId)
        {
            try
            {
                var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity>((u, ou) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                })
                .Where((u, ou) => u.IsDeleted == 0 && ou.IsLeader == 1 && ou.OrgId == orgId)
                .Select((u, ou) =>new LeaderInfo{ 
                    UserId=ou.UserId,
                    UserName=u.RealName,
                    WXOpenId=ou.WXOpenId,
                    Mobile=u.Mobile
                }).FirstAsync();
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 根据用户ID获取用户信息包括 微信OpenID
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<LeaderInfo> GetUserWXInfoById(Guid id,int orgid)
        {
            try
            {
                var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity>((u, ou) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                })
                .Where((u, ou) => u.IsDeleted == 0 && u.Id==id&& ou.OrgId== orgid)
                .Select((u, ou) => new LeaderInfo
                {
                    UserId = ou.UserId,
                    UserName = u.RealName,
                    WXOpenId = ou.WXOpenId,
                    Mobile = u.Mobile
                }).FirstAsync();
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }
        public async Task<TasUserEntity> GetUserInfo(Guid id, int orgid)
        {
            try
            {
                var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity>((u, ou) => new object[] {
                    JoinType.Left, ou.UserId == u.Id,
                })
                .Where((u, ou) => u.IsDeleted == 0 && u.Id == id && ou.OrgId == orgid)
                .Select((u, ou) => new TasUserEntity
                {
                    Avatar=u.Avatar,
                    CreatedTime = u.CreatedTime,
                    CreatedUserId = u.CreatedUserId,
                    CreatedUserName = u.CreatedUserName,
                    Email = u.Email,
                    EmailIsVerified = u.EmailIsVerified,
                    IDCardNO = u.IDCardNO,
                    Id = u.Id,
                    IsDeleted = u.IsDeleted,
                    IsDisabled = u.IsDisabled,
                    IsFrozen = u.IsFrozen,
                    IsSuperAdmin = u.IsSuperAdmin,
                    LastOrgId =u.LastOrgId,
                    Mobile =u.Mobile,
                    MobileIsVerified =u.MobileIsVerified,
                    NickName =u.NickName,
                    Password =u.Password,
                    PasswordSalt =u.PasswordSalt,
                    PersonalNote =u.PersonalNote,
                    Phone =u.Phone,
                    QQAccount =u.QQAccount,
                    RealName =u.RealName,
                    Remark =u.Remark,
                    Sex =u.Sex,
                    Sort =u.Sort,
                    UpdatedTime =u.UpdatedTime,
                    UpdatedUserId =u.UpdatedUserId,
                    UpdatedUserName =u.UpdatedUserName,
                    UserName =u.UserName,
                    WxAccount =ou.WXOpenId
                }).FirstAsync();
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }
        /// <summary>
        /// 根据工号和手机号获取一个旅游顾问实体对象
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<TasOrgUserDto> GetByJobNumberOrMobile(int topOrgId, string keywords)
        {
            try
            {
                var topLevelPath = $"{topOrgId},";
                var result =await _unitOfWork.QueryClient.Queryable<TasUserEntity,TasOrgUserMapEntity,OrganizationEntity>(( u,ou, o) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                    JoinType.Inner, ou.OrgId ==o.Id
                })
                //.Where(( u,ou) => u.IsDeleted == 0 && ou.IsLeader == 1 && (o.OrgLevel == (int)OrgLevel.Store|| o.OrgLevel == (int)OrgLevel.DirectlyUnder))
                .Where(( u,ou, o) => (ou.JobNumber == keywords || (u.Mobile == keywords && u.MobileIsVerified == 1))&&o.LevelPath.StartsWith(topLevelPath) && u.IsDeleted == 0 && u.IsDisabled == 0 && u.IsFrozen == 0 && ou.IsDisabled == 0 && ou.IsFrozen == 0)
                    .Select((u, ou, o) => new TasOrgUserDto()
                    {
                        Id = u.Id,
                        Mobile = u.Mobile,
                        MobileIsVerified = u.MobileIsVerified,
                        Email = u.Email,
                        RealName = u.RealName,
                        Sex = u.Sex,
                        Avatar = u.Avatar,
                        HxUserName = ou.HxUserName,
                        JobNumber = ou.JobNumber,
                        OrgId = o.Id,
                        SettlementOrgId = 0,
                        OrgName = o.Name,
                        OrgLevel = o.OrgLevel,
                        OrgLevelPath = o.LevelPath
                    }).FirstAsync();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 根据orgId获取org的负责人
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<TasOrgUserDto>> GetRandomOrgUserListByOrgId(int orgId)
        {
            try
            {
                var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity,OrganizationEntity>((u, ou, o) => new object[] {
                    JoinType.Inner, u.Id == ou.UserId,
                    JoinType.Inner, o.Id == ou.OrgId,
                })
                    .Where((u, ou, o) => ou.OrgId == orgId && u.IsDeleted == 0 && u.IsDisabled == 0 && u.IsFrozen == 0 && ou.IsDisabled == 0 && ou.IsFrozen == 0)
                    .OrderBy((u, ou, o) => ou.IsLeader, OrderByType.Desc)
                    .Select((u, ou, o) => new TasOrgUserDto()
                    {
                        Id = u.Id,
                        Mobile = u.Mobile,
                        Email = u.Email,
                        RealName = u.RealName,
                        Sex = u.Sex,
                        Avatar = u.Avatar,
                        HxUserName = ou.HxUserName,
                        JobNumber = ou.JobNumber,
                        OrgId=o.Id,
                        SettlementOrgId =0,
                        OrgName = o.Name,
                        OrgLevel = o.OrgLevel,
                        OrgLevelPath = o.LevelPath
                    })
                    .ToListAsync();
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }

        }

        /// <summary>
        /// 修改昵称与头像
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateNickNameAndAvatar(TasUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new
            {
                it.Avatar,
                it.NickName,
                it.UpdatedUserId,
                it.UpdatedUserName,
                it.UpdatedTime,
            }).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 获取带org信息的旅游顾问
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<TasOrgUserDto> GetByUserIdAndOrgIdWithOrg(Guid userId, int orgId)
        {
            try
            {
                var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity,OrganizationEntity>((u, ou, o) => new object[] {
                    JoinType.Inner, u.Id == ou.UserId,
                    JoinType.Inner, o.Id == ou.OrgId,
                })
                    .Where((u, ou, o) => ou.UserId == userId && ou.OrgId == orgId && u.IsDeleted == 0 && u.IsDisabled == 0 && u.IsFrozen == 0 && ou.IsDisabled == 0 && ou.IsFrozen == 0)
                    .Select((u, ou, o) => new TasOrgUserDto()
                    {
                        Id = u.Id,
                        Mobile = u.Mobile,
                        Email = u.Email,
                        RealName = u.RealName,
                        Sex = u.Sex,
                        Avatar = u.Avatar,
                        HxUserName = ou.HxUserName,
                        JobNumber = ou.JobNumber,
                        OrgId=o.Id,
                        SettlementOrgId =0,
                        OrgName = o.Name,
                        OrgLevel = o.OrgLevel,
                        OrgLevelPath = o.LevelPath
                    })
                    .FirstAsync();
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }

        }
    }
}
